package org.dromara.admin.ocr.service;

import cn.hutool.core.bean.BeanUtil;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.admin.domain.bo.UserDetailBo;
import org.dromara.admin.domain.bo.UserEmergencyContactBo;
import org.dromara.admin.domain.vo.UserDetailVo;
import org.dromara.admin.service.IUserDetailService;
import org.dromara.admin.service.IUserEmergencyContactService;
import org.dromara.admin.utils.OcrUtil;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.satoken.utils.LoginHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * OCR服务
 *
 * @author Lion Li
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class OcrService {

    private static final String APP_ID = "d75j5fx8f1yrza4o6bdxf4fozw5ghwc8"; // 应用id
    private static final String APP_KEY = "5y9xvgfz735c1p75vt0cu0jmsa63l2wic49b09s0x2xzcyjm29oa5ngqlehnizzv";

    private static final String API_URL = "https://hd-cloud.test.nbhdian.com";

    private static final String ESTATE_OCR_URL = "/api/aliyuns/estateOcr"; // 房产证识别
    private static final String IDCARD_OCR_URL = "/api/datapay/idcardOcr"; // 身份证识别
    private static final String PERSONAL_3_URL = "/api/datapay/personal3"; // 个人三要素识别

    private final IUserDetailService userDetailService;

    private final IUserEmergencyContactService userEmergencyContactService;

    /** 房产证 OCR */
    public JsonNode estateOcr(String url) {
        Map<String, Object> data = new HashMap<>();
        data.put("url", url);
        return OcrUtil.callOcr(API_URL + ESTATE_OCR_URL, APP_ID, APP_KEY, data);
    }

    /** 身份证 OCR */
    public JsonNode idCardOcr(String imageId) {
        Map<String, Object> data = new HashMap<>();
        data.put("imageId", imageId);
        return OcrUtil.callOcr(API_URL + IDCARD_OCR_URL, APP_ID, APP_KEY, data);
    }

    /**
     * 个人三要素
     * @param req
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JsonNode personal3(Map<String, Object> req) {
        Map<String, Object> data = new HashMap<>();
        data.put("name", req.get("name"));
        data.put("id_card", req.get("id_card"));
        data.put("mobile", req.get("mobile"));
        JsonNode jsonNode = OcrUtil.callOcr(API_URL + PERSONAL_3_URL, APP_ID, APP_KEY, data);

        // 获取用户紧急联系人列表
        List<Map<String, String>> userEmergencyContact = (List<Map<String, String>>) req.get("user_emergency_contact");

        // 判断返回状态
        int result = jsonNode.path("data").path("result").asInt(-1);

        System.out.println("个人三要素result：" +  result);
        if (result == 1) {
            // 比对成功，入库
            Long userId = (Long) req.get("user_id");
            UserDetailVo userDetailVo = userDetailService.queryById(userId);
            userDetailVo.setRealName(req.get("name").toString());
            userDetailVo.setIdentityCard(req.get("id_card").toString());
            userDetailVo.setIdCardFront(req.get("id_card_front").toString());
            userDetailVo.setIdCardBack(req.get("id_card_back").toString());
            userDetailService.updateByBo(BeanUtil.copyProperties(userDetailVo, UserDetailBo.class));

            // 保存用户紧急联系人
            if (userEmergencyContact != null && !userEmergencyContact.isEmpty()) {
                for (Map<String, String> map : userEmergencyContact) {
                    UserEmergencyContactBo bo = new UserEmergencyContactBo();
                    bo.setUserId(userId);
                    bo.setContactName(map.get("contact_name"));
                    bo.setContactPhone(map.get("contact_phone"));
                    bo.setRelation(map.get("relation"));
                    bo.setRemark(map.getOrDefault("remark", null));
                    userEmergencyContactService.insertByBo(bo);
                }
            }
        } else {
            // 失败，不入库，抛出异常给前端
            throw new ServiceException("三要素校验失败!");
        }
        return jsonNode;
    }
}
